package controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sql.UserStoryDao;

/**
 * Servlet implementation class UpdateBacklogPriority
 */
@WebServlet("/UpdateBacklogPriority")
public class UpdateBacklogPriority extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateBacklogPriority() {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id = request.getParameter("id");
		String listString = request.getParameter("list");
		int sprintId = 0;

		if (! id.equals("backlog-list")) { // if sprint backlog
			// get sprint id
			String sprintIdString = id.replaceFirst("sprint-", "");
			sprintIdString = sprintIdString.replaceFirst("-list", "");
			sprintId = Integer.parseInt(sprintIdString);
		}
		
		prioritizeBacklogItems(listString, sprintId);
	}

	public static void prioritizeBacklogItems(String listString, int sprintId) {
		prioritizeBacklogItems(null, listString,sprintId);
	}

	// also used by SprintViewDao.cancelSprint()
	public static void prioritizeBacklogItems(Connection conn, String listString, int sprintId) {
		// get list
		if (! listString.isEmpty()) {
			String[] priorityList = listString.split(",");
			for (int i = 0; i < priorityList.length; i++) {
				int itemId = Integer.parseInt(priorityList[i]);
				UserStoryDao userStoryDao = new UserStoryDao();
				try {
					userStoryDao.prioritizeBacklogItem(conn, sprintId, itemId, i + 1);
				} catch (ClassNotFoundException | SQLException e) {
					e.printStackTrace();
				}
			}
			
		}
	}

}
